package com.cjkj.agent.service.impl;

import com.cjkj.agent.domain.TAgentAreaInfo;
import com.cjkj.agent.domain.vo.AgentAreaVo;
import com.cjkj.agent.mapper.TAgentAreaInfoMapper;
import com.cjkj.agent.service.ITAgentAreaInfoService;
import com.cjkj.common.exception.ServiceException;
import com.cjkj.common.utils.DateUtils;
import com.cjkj.common.utils.bean.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.cjkj.common.utils.SecurityUtils.getUsername;

/**
 * 代理商代理区域信息Service业务层处理
 * 
 * @author cjkj
 * @date 2025-10-11
 */
@Service
public class TAgentAreaInfoServiceImpl implements ITAgentAreaInfoService 
{
    @Resource
    private TAgentAreaInfoMapper tAgentAreaInfoMapper;

    /**
     * 查询代理商代理区域信息列表
     * @param agentId 代理商ID
     * @return 代理商代理区域信息
     */
    @Override
    public List<AgentAreaVo> selectAgentAreaData(String agentId)
    {
        return tAgentAreaInfoMapper.selectAgentAreaDataByAgentId(agentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setAgentAreaInfo(String agentId, List<AgentAreaVo> areaParams) {
        if(areaParams == null || areaParams.isEmpty()) {
            throw new ServiceException("代理区域不能为空！");
        }

        // 删除被取消的代理区域
        List<AgentAreaVo> needDel = tAgentAreaInfoMapper.selectNeedDeleteDataByAgentId(agentId, areaParams);
        Long[] ids = needDel.stream().map(AgentAreaVo::getInfoId).toArray(Long[]::new);
        int del = 0;
        if(ids.length > 0) {
            del = tAgentAreaInfoMapper.deleteTAgentAreaInfoByInfoIds(ids);
        }

        // 保存新增的代理区域
        String username = getUsername();
        Date nowDate = DateUtils.getNowDate();
        int save = 0;
        for (AgentAreaVo agentAreaVo : areaParams) {
            TAgentAreaInfo obj = tAgentAreaInfoMapper.selectByAreas(agentId, agentAreaVo.getProvince(), agentAreaVo.getCity(), agentAreaVo.getArea());
            if(obj == null) {
                TAgentAreaInfo tAgentAreaInfo = new TAgentAreaInfo();
                BeanUtils.copyBeanProp(tAgentAreaInfo, agentAreaVo);
                tAgentAreaInfo.setAgentId(agentId);
                tAgentAreaInfo.setCreateBy(username);
                tAgentAreaInfo.setCreateTime(nowDate);
                tAgentAreaInfo.setUpdateBy(username);
                tAgentAreaInfo.setUpdateTime(nowDate);
                save += tAgentAreaInfoMapper.insertTAgentAreaInfo(tAgentAreaInfo);
            } else {
                save += 1;
            }
        }

        if(del == ids.length && save == areaParams.size()) {
            return 1;
        }
        return 0;
    }

}
